package com.dragon.logical.service.customer.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.model.ResultCode;
import com.dragon.common.model.exception.CustomException;
import com.dragon.logical.service.customer.AccountrecordssService;
import com.dragon.repository.config.annotation.DataScope;
import com.dragon.repository.entity.Accountrecordss;
import com.dragon.repository.entity.Customer;
import com.dragon.repository.mapper.AccountrecordssMapper;
import com.dragon.repository.mapper.CustomerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 客户联系记录 服务实现类
 * </p>
 *
 * @author sy
 * @since 2023-06-19
 */
@Service
public class AccountrecordssServiceImpl extends ServiceImpl<AccountrecordssMapper, Accountrecordss> implements AccountrecordssService {

    @Autowired
    AccountrecordssMapper aMapper;

    @Autowired
    CustomerMapper cMapper;


    @Override
    @DataScope(deptAlias = "",deptField = "department_id",adminAlias = "",adminField = "record_id")
    public Page<Accountrecordss> listAccountPage(String search, Integer page, Integer limit) {
        Page<Accountrecordss> aPage = new Page<>(page,limit);
        return aMapper.selectAccount(aPage,search);
    }

    @Override
    public Integer addAccount(Accountrecordss convert) {
        Customer customer = cMapper.selectById(convert.getCustomerId());
        if (customer == null){
            throw new CustomException(ResultCode.DATA_ALREADY_EXISTS);
        }
        convert.setVisitName(customer.getCustomerName());
        convert.setCreateTime(DateUtil.date());
        aMapper.insert(convert);
        return customer.getId();
    }


    @Override
    public void updateAccount(Accountrecordss convert) {
        Accountrecordss accountrecordss = aMapper.selectById(convert.getId());
        if (accountrecordss == null) {
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        convert.setUpdateTime(DateUtil.date());
        aMapper.updateById(convert);
    }

    @Override
    public void deleteAccount(Integer id) {
        Accountrecordss accountrecordss = aMapper.selectById(id);
        if (accountrecordss == null) {
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        aMapper.fakeDelete(id);
    }

}
